<template>
  <search-table
    :data="systemList"
    :columns="systemCol"
    :page.sync="queryParams.pageIndex"
    :size.sync="queryParams.pageSize"
    :total="systemTotal"
    :loading="systemListLoading"
    @queryFun="getNewData">
    <template slot="search">
      <Button type="primary" ghost class="md-add-jh" @click="relativePart()">关联业务系统</Button>
      <Button type="primary" ghost class="md-add-jh" @click="showModal(null)">创建业务系统</Button>
      <Divider type="vertical" style="margin: 10px 0px 10px 10px;" />
      <Input v-model.trim="queryParams.name"  clearable placeholder="部件名称" @on-change="searchSystemName" style="width: 180px;margin-left: 15px" />
      <Button class="header-btn" type="primary" ghost style="height: 32px;margin-left: 5px;" @click="refreshSystemList()">
        <i class="el-icon-refresh-right" />
      </Button>
    </template>
    <!--创建镜像"-->

    <Modal v-model="modalData.show" :mask-closable="false" width="600"
           :title="`${isUpgrade ? '升级' : isAdd ? '创建业务系统' : '修改业务系统'}`"
           @on-visible-change="changeVisible"
    >
      <Form ref="formInline" :model="formInline" :rules="ruleInline" :label-width="120" style="width: 500px">
        <template v-if="upgradeType === 'add'">
          <FormItem prop="name" label="业务系统名称" key="name">
            <Input clearable v-model="formInline.name"></Input>
          </FormItem>
          <FormItem prop="institutionId" label="所属单位" key="institutionId">
            <Select filterable transfer filterable clearable v-model="formInline.institutionId">
              <Option v-for="item in institutionList" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
          </FormItem>
          <FormItem prop="productId"  label="关联产品版本" key="productId">
            <Input disabled v-model="showProductName"></Input>
          </FormItem>
          <FormItem prop="status"  label="运营状态" key="status">
            <Select filterable transfer filterable clearable v-model="formInline.status">
              <Option v-for="item in stateOptions" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
          </FormItem>
          <FormItem prop="testNetinfoId" label="关联网络" key="testNetinfoId">
            <Select filterable transfer filterable clearable v-model="formInline.testNetinfoId" placeholder="" @on-change="changeNetInfo" >
              <!--             :disabled="!isAdd"-->
              <Option v-for="item in netInfoList" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
          </FormItem>
          <FormItem prop="assetNetworkMeshId" label="网络区域" key="assetNetworkMeshId">
            <Select filterable transfer filterable clearable v-model="formInline.assetNetworkMeshId" placeholder="" >
              <!--              :disabled="!isAdd"-->
              <Option v-for="item in netMeshList" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
          </FormItem>
          <FormItem prop="industry" label="行业" key="industry">
            <Select filterable transfer filterable clearable v-model="formInline.industry" placeholder="">
              <Option v-for="item in industryList" :value="item.dictid" :key="item.dictname">{{ item.dictname }}</Option>
            </Select>
          </FormItem>
          <FormItem prop="description" label="简述" key="description">
            <Input type="textarea" clearable v-model="formInline.description"></Input>
          </FormItem>
          <FormItem prop="region" label="区域" class="my-form-item" key="region">
            <Input clearable v-model="formInline.region"></Input>
          </FormItem>
          <FormItem prop="longitude" label="经度" class="my-form-item" key="longitude" >
            <Input clearable v-model="formInline.longitude"></Input>
            <Tooltip style="margin-left: 10px;" transfer max-width="200" content="由软件厂商提供的按照ISO/IEC 19770-2:2015规范的标记识别符" placement="top">
              <Icon type="ios-alert" class="ios-alert" />
            </Tooltip>
          </FormItem>
          <FormItem prop="latitude" label="纬度" key="latitude" class="my-form-item">
            <Input clearable v-model="formInline.latitude"></Input>
            <Tooltip style="margin-left: 10px;" transfer max-width="200" content="通用平台枚举，是指MITRE或者NIST提供的CPE V2.2或者CPE V2.3的URI" placement="top">
              <Icon type="ios-alert" class="ios-alert" />
            </Tooltip>
          </FormItem>
          <FormItem prop="logo" label="上传图标" key="logo">
            <itemUpload ref="fileUpload"
                        @upload-success="val=>uploadSuccess(val,'logo')"
                        :formatArr="['png','jpg']"
                        :showUploadList="true"
                        uploadText="上传文件"
                        @clearFile="setClear('logo')"
                        fileType="files"></itemUpload>
          </FormItem>
        </template>
      </Form>
      <div slot="footer" class="footer">
        <Button @click="modalData.show = false">取消</Button>
        <Button @click="saveSystem" :loading="modalData.loading" type="primary">确定</Button>
      </div>
    </Modal>
    <Modal
      v-model="detailModalData.show"
      title="业务系统详情"
      footer-hide
      class="my-modal">
      <div class="item-table">
        <p>
          <span class='label'>业务名称</span>
          <span>{{detailInfo.name}}</span>
        </p>
        <p>
          <span class='label'>所属单位</span>
          <span>{{detailInfo.institutionName}}</span>
        </p>
        <p>
          <span class='label'>对外URL</span>
          <span>{{detailInfo.urls&&detailInfo.urls.map(m=>m.url).join(',')}}</span>
        </p>
        <p>
          <span class='label'>关联网络</span>
          <span>{{detailInfo.testNetinfoName}}</span>
        </p>
        <p>
          <span class='label'>关联区域</span>
          <span>{{detailInfo.assetNetworkMeshName}}</span>
        </p>
      </div>
    </Modal>
    <Modal
      v-model="deployModal"
      title="部署记录查看"
      :footer-hide="true"
      :mask-closable="false"
      :width="800"
    >
      <search-table :columns="systemDeployRecordCol"
               :data="systemDeployRecordList"
               :loading="systemDeployRecordLoading"
               :total="systemDeployRecordTotal"></search-table>
    </Modal>
    <drawers @on-close="getNewData" ref="drawerUrlList" title="配置访问地址列表" :width="1200">
      <url-list :businessSystemId="currentInfo.id" ref="urlList"></url-list>
    </drawers>
    <relativeSystem ref="relativeSystem" @refresh="getNewData" :productId="productInfo.id"></relativeSystem>
  </search-table>
</template>
<script>
import {relativeSystemCol} from "../configData/relativeSystemCol";
import $ from 'jquery'
import {getIndustryList, getNetMeshList, getNetInfoList, getUnitListSystem, getUnitList} from '../logic/assetLogic'
import encryption from '@/libs/encryption.js'
import * as paramsConfig from '../../paramsConfig'
import urlList from './urlList'


import itemUpload from '../../components/item-upload/index.vue'
import drawers from '../../components/drawers.vue'
import relativeSystem from './relativeSystem.vue'
import {
  querySystemList,
  addSystems,
  updateSystem,
  deleteSystem,
  querySystemDeployRecord
} from '../api/system.js'
export default {
  components: {itemUpload,drawers,urlList,relativeSystem},
  props: {
    productInfo: {
      type: Object,
      default: ()=>{}
    }
  },
  data () {
    return {
      currentInfo:{},
      deployModal:false,
      systemDeployRecordList:[],
      systemDeployRecordTotal:0,
      systemDeployRecordLoading:false,
      systemDeployRecordCol:[
        {title:'部件名称',key:'productPartName'},
        {title:'IP资产',key:'ip'},
        {title:'端口',key:'port'},
        {title:'网络区域',key:'assetNetworkMeshName'},
        {title:'网络名称',key:'testNetinfoName'}
      ],

      assetCategoryList:[],
      unitList:[],
      vendorList:[],

      stateOptions:paramsConfig.SYSTEM_STATE_OPTIONS,

      systemList:[],

      institutionList:[],
      industryList:[],
      netMeshList:[],
      netInfoList:[],

      systemListLoading:false,
      systemTotal:0,

      formInline: {
        name: '',
        institutionId:'a',
        productId: this.productInfo.id,
        status:undefined,
        testNetinfoId:'',
        assetNetworkMeshId:'',
        industry: '',
        objectId: '',
        description: '',
        region:'',
        logo: '',
        longitude:undefined,
        latitude:undefined
      },
      ruleInline: {
        name: [
          { required: true, message: '业务名称不能为空', trigger: 'blur,change' }
        ],
        institutionId: [
          { required: true,  message: '所属单位不能为空', trigger: 'blur,change' }
        ],
        productId: [
          { required: true,  message: '关联产品不能为空', trigger: 'change' }
        ],
        status: [
          { required: true, type:'number',message: '运行状态不能为空', trigger: 'blur,change' }
        ]
      },
      modalData: {
        show: false,
        loading: false
      },
      isAdd: false,
      upgradeType: 'add',
      typeOptions: ['软件', '硬件'],
      isUpgrade: false,
      file: {},
      optionList: [],
      detailModalData: {
        show: false
      },
      detailInfo: {},

      queryParams:{
        pageIndex:1,
        pageSize:10
      },
      // 用户信息
      USER_ID: '',
      isRootDesinger: '',
      distributed: false,
      // 页面设置
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      setTableHei: 'auto',
      showDefImg: false,
      showImgList: false,
      // 镜像列表
      assetListLoading: false,
      assetCategory: [],
      unit: '',
      industry: '',
      systemCol:[],
      actionButtons: [
            {
              txt: '查看',
              on:{
                click:(data,e) => {
                  this.detailModalData.show = true
                  this.detailInfo = data
                }
              },
            },
            {
              txt: '修改',
              on:{
                click:(data,e) => {
                  this.showModal(data)
                }
              },
            },
            {
              txt: '部署情况',
              on:{
                click:(data,e) => {
                  this.currentInfo = data;
                  this.showDeployModal()
                }
              },
            },
            {
              txt: '访问地址',
              on:{
                click:(data,e) => {
                  this.currentInfo = data;
                  this.$refs.drawerUrlList.openDrawer();
                  this.$refs.urlList.queryList(data.id);
                }
              },
            },
            {
              txt: '删除',
              tooltip: true,
              type: 'delete',
              title: '确定要删除这个部件吗？',
              on:{
                click:(data,e) => {
                  this.deleteItem(data.id)
                }
              },
              disabled:(data)=>data.isUsed
            }
      ],
      searchImageName: '',
      assetModelInput: '',
      creatByMeModal: false,
      // 创建和修改镜像
      imageID: '',
      assetModal: false,
      updateUrl: `/api/resource-manager/image/add`,
      addAssetBtnLoading: false,
      productTypeIds:[],



      setDisabled: false,
      isCreate: true,
      //profile
      profileList: [],
      // 镜像用户
      showImgUser: false,
      formIsShow: false,
      imageUserId: '',
      addUserLoading: false,
      createPort: '22',
      isCreatUser: false,
      isClound: false,
      imgUserList: [],
      flag: 0, //标记成功的次数
      filedArr: [],//承装切片的容器
      oldTime: 0,//初始化时间
      progressflag: false,//控制进度条的展示
      fileName: '',
      saveTargetStatusArr: [],//存储中间状态
      messageSwitch: false,//解决鼠标移入失败或者成功验证状态气泡框位置错乱设置的开关
      systemVersion:[]
    }
  },
  computed: {
    showProductName(){
      return `${this.productInfo.name}(${this.productInfo.version})`
    }
  },
  watch: {


  },
  created () {
    // 获取用户id
    let November = sessionStorage.getItem('November')
    November = JSON.parse(encryption.SelfUseDecrypt(November))
    this.USER_ID = November.userId
    this.isRootDesinger = November.isRootDesinger
    this.distributed = November.distributed
    // this.distributedRange = this.$store.state.user.distributedRange
  },
  mounted () {
    this.systemCol = relativeSystemCol(this);
    let getPage = this.$route.query.page ? parseInt(this.$route.query.page) : 1
    this.queryParams.pageIndex = getPage
    this.getNewData()
  },
  methods: {
    getNewData(isRefresh){
      // 列表
      if (!isRefresh) { // 非刷新操作才需要展示等待中的画面
        this.partListLoading = true
      }
      this.queryParams.productId = this.productInfo.id;
      querySystemList(this.queryParams)
        .then(res => {
          if (res.code == 1) {
            this.systemTotal =res.data.total;
            this.systemList = res.data.items
          }
          this.systemListLoading = false
        })
        .catch(err => {
          this.systemListLoading = false
        })
    },
    changeNetInfo(netinfoId){
      getNetMeshList(this,'netMeshList',netinfoId);
    },
    showDeployModal(){
      this.deployModal = true;
      this.getSystemDeployRecord();
    },
    getSystemDeployRecord(){
      this.systemDeployRecordLoading = true;
      let params = {
        pageIndex:1,
        pageSize:10
      }
      querySystemDeployRecord(this.currentInfo.id,params).then(res=>{
        if(res.code===1){
          this.systemDeployRecordList = res.data.items;
          this.systemDeployRecordTotal = res.data.total
        }else{
          this.$Message.error(res.message)
        }

      }).finally(()=>{
        this.systemDeployRecordLoading = false;
      })
    },
    searchSystemName(){
      this.queryParams.pageIndex = 1;
      this.getNewData();
    },
    relativePart(){
      this.$refs.relativeSystem.openModal();
    },
    refreshSystemList(){
      this.queryParams = {
        pageIndex:1,
        pageSize:10,
      }
      this.getNewData()
    },
    uploadSuccess(val){
      this.file = val
      //设置表单数据并触发表单检测
      this.$set(this.formInline, 'logo', val.fileId)
    },
    setClear(){
      this.file = {}
      this.$set(this.formInline, 'logo', '')
    },
    // 下载文件
    downloadFile(item) {
      if (!item.fileId) {
        return
      }
      let a = document.createElement('a');
      let fileName = item.fileName; //filename名称截取
      a.href = `/api/minio/download/${item.fileId}`;
      a.download = fileName; //命名下载名称
      a.click(); //点击触发下载
    },
    // 保存数据
    saveSystem() {
      this.$refs.formInline.validate(valid => {
        if (valid) {
          this.modalData.loading = true
          let apiName = this.isAdd ? addSystems : updateSystem
          if (this.isAdd) { // 创建操作确认把id删掉，避免造成错误
            delete this.formInline.id
          }
          apiName(this.formInline).then(({ code, message }) => {
            if (code !== 1) {
              this.$Message.warning(message)
              return
            }
            // 创建成功
            this.$Message.success(`${this.isUpgrade ? '升级' : this.isAdd ? '创建' : '修改'}业务系统成功`)
            this.getNewData()
            this.modalData.show = false
          }).catch(() => {
            this.$Message.error(`${this.isUpgrade ? '升级' : this.isAdd ? '创建' : '修改'}业务系统异常`)
          }).finally(() => {
            this.modalData.loading = false
          })
        }
      })
    },

// 删除部件
    deleteItem(id) {
      deleteSystem([id]).then(({ code, message }) => {
        if (code !== 1) {
          this.$Message.warning(message)
          return
        }
        this.$Message.success(`删除成功`)
        // 删除后展示当前页，当前页没有数据展示前一页
        this.queryParams.pageIndex = (this.systemList.length === 1 && this.queryParams.pageIndex > 1) ?
          this.queryParams.pageIndex - 1 : this.queryParams.pageIndex;
        this.getNewData();
      }).catch(() => {
        this.$Message.error(`删除部件异常`)
      })
    },
    // 打开模态框
    // 打开模态框
    showModal(data, isUpgrade) {
      //获取select的相关数据
      getIndustryList(this,'industryList');
      getNetInfoList(this,'netInfoList');
      getNetMeshList(this,'netMeshList');
      //getUnitListSystem(this,'institutionList');
      getUnitList(this,'institutionList')
      this.isAdd = !data
      this.modalData.show = true
      let obj = data || this.formInline
      this.formInline = Object.assign({ productId: this.productInfo.id }, obj);
      this.$nextTick(() => {
        if(!this.isAdd){
          let { logo,testNetinfoId } =obj;
          this.changeNetInfo(testNetinfoId)
          if (logo) {
            this.$refs.fileUpload && this.$refs.fileUpload.showDefaultList({filePath: logo})
          } else {
            this.$refs.fileUpload && this.$refs.fileUpload.showDefaultList(null)
          }
        }else{
          this.$refs.fileUpload && this.$refs.fileUpload.showDefaultList(null)
        }
      })
    },
    // 打开关联部件的模态框，初始化数据
    getPartOptions() {
      Promise.all([queryProductPartList({
        pageIndex: 1,
        pageSize: 2147483646,
        productId: this.productId
      }), queryProductPartList({
        pageIndex: 1,
        pageSize: 2147483646,
      })]).then(res => {
        let selfIds = [], allOptionList = []
        res.forEach((item, index) => {
          let { code, data } = item
          if (index === 0) { // 本产品已有的部件
            if (code === 1) {
              selfIds = (data.items || []).map(item => item.id)
            }
          } else { // 其他部件
            if (code === 1) {
              allOptionList = data.items || []
            }
          }
        })
        this.optionList = allOptionList.filter(item => !selfIds.includes(item.id))
      })
    },
    // 隐藏模态框时，重置表单数据
    changeVisible(type) {
      if (!type) {
        this.$refs.formInline.resetFields()
        this.upgradeType = 'add'
        this.modalData.loading = false
      }
    },
  },
  beforeDestroy () {

  }
}
</script>
<style scoped>
.my-form-item /deep/ .ivu-form-item-content{
  display: flex;
}
 .item-table {
   display: table;
   width: 100%;
   border: 1px solid #eee;
   table-layout: fixed;
   word-break: break-all;
 }
.item-table p {
  display: table-row;
  line-height: 36px;
  text-align: center;
}
.item-table p span {
  display: table-cell;
  border-bottom: 1px solid #eee;
}
.ios-alert {
  /* position: absolute;
        top: -44px;
        right: -404px; */
  color: orange;
  font-size: 16px;
  cursor: pointer;
}
.too {
  position: absolute;
  left: 113px;
  top: -1px;
}
</style>
